package com.leoandroid.tool.toolsbox.largeread.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.leoandroid.tool.toolsbox.largeread.camera.CameraProxy;
import com.leoandroid.tool.toolsbox.largeread.fragment.MagnifierFragment;
import com.leoandroid.tool.toolsbox.largeread.utils.ImageUtils;
import com.leoandroid.tool.toolsbox.largeread.utils.SPUtil;
import com.leoandroid.tool.toolsbox.largeread.view.CameraSurfaceView;
import com.leoandroid.tool.toolsbox.largeread.R;
import com.leoandroid.tool.toolsbox.largeread.utils.ToolUtils;

public class SurfaceCameraActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "SurfaceCameraActivity";

    private ImageView layoutBack;
    private ImageView lSwitchCamera;
    private TextView tvTackPhoto;
    private FrameLayout fMagnifierAlbum;
    private FrameLayout fTorch;
    private ImageView ivTorch;
    private CameraSurfaceView mCameraView;
    private RangeSeekBar brightSeekBar;
    private RangeSeekBar zoomSeekBar;
    private ImageView previewIv;

    private CameraProxy mCameraProxy;
    private Camera.Parameters parameters;// 照相机参数集

    private float mZoomOldValue;

    private static final int IMAGE_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        if (ToolUtils.getHeightStatusBar(this) > 0) {
            findViewById(R.id.layout_padding).setPadding(0, ToolUtils.getHeightStatusBar(this), 0, 0);
        }
        ToolUtils.setStatusBarHomeTransparent(this);
        initView();
    }

    private void initView() {
        layoutBack = findViewById(R.id.magnifier_back);
        layoutBack.setOnClickListener(this);
        lSwitchCamera = findViewById(R.id.switch_camera);
        lSwitchCamera.setOnClickListener(this);
        tvTackPhoto = findViewById(R.id.take_photo);
        tvTackPhoto.setOnClickListener(this);
        fMagnifierAlbum = findViewById(R.id.magnifier_album);
        previewIv = findViewById(R.id.preview);
        fMagnifierAlbum.setOnClickListener(this);
//        mPictureIv.setImageBitmap(ImageUtils.getLatestThumbBitmap());
        mCameraView = findViewById(R.id.camera_view);
        mCameraProxy = mCameraView.getCameraProxy();
        fTorch = findViewById(R.id.layout_torch);
        fTorch.setOnClickListener(this);
        ivTorch = findViewById(R.id.iv_torch);

        brightSeekBar = findViewById(R.id.bright_seek_bar);
        zoomSeekBar = findViewById(R.id.zoom_seek_bar);
        brightSeekBar.setRange(0f, 100f, 10f);
        // 获取系统亮度
        int curBrightness = 10;
        try {
            curBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        int finalCurBrightness = curBrightness;
        brightSeekBar.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                Log.d(TAG, "leftValue = " + leftValue + ", rightValue =  " + rightValue + ", isFromUser = " + isFromUser);
                int bValue = (int) (leftValue / 100 * 255);
                changeAppBrightness(SurfaceCameraActivity.this, bValue);
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });
        zoomSeekBar.setRange(0f, 100f, 10f);
        zoomSeekBar.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
//                Log.d(TAG, "leftValue = " + leftValue + ", rightValue =  " + rightValue + ", isFromUser = " + isFromUser);
                if (leftValue > mZoomOldValue) {
                    mCameraProxy.handleZoom(true);
                } else if (leftValue < mZoomOldValue) {
                    mCameraProxy.handleZoom(false);
                }
                mZoomOldValue = leftValue;
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.magnifier_back) {
            finish();
        } else if (id == R.id.switch_camera) {
            mCameraProxy.switchCamera();
            mCameraProxy.startPreview(mCameraView.getHolder());
        }
//        else if (id == R.id.take_photo) {
//            requestWriteAndRead();
//        }
        else if (id == R.id.magnifier_album) {//在这里跳转到手机系统相册里面
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, IMAGE_REQUEST_CODE);
        } else if (id == R.id.layout_torch) {
            parameters = mCameraProxy.getCamera().getParameters();// 获取相机参数集
            if (parameters.getFlashMode() == null) {
                Toast.makeText(SurfaceCameraActivity.this, "无闪光灯", Toast.LENGTH_SHORT).show();
            } else if (Camera.Parameters.FLASH_MODE_TORCH.equals(parameters.getFlashMode())) {
                ivTorch.setImageResource(R.mipmap.ic_enlarge_flashlight_off);
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                mCameraProxy.getCamera().setParameters(parameters);

            } else if (Camera.Parameters.FLASH_MODE_OFF.equals(parameters.getFlashMode())) {
                ivTorch.setImageResource(R.mipmap.ic_enlarge_flashlight_on);
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                mCameraProxy.getCamera().setParameters(parameters);
            }
        }
    }

    // 根据亮度值修改当前window亮度
    public void changeAppBrightness(Context context, int brightness) {
        Window window = ((Activity) context).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    private final Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // 根据拍照所得的数据创建位图
            final Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
            previewIv.setImageBitmap(bm);
            mCameraProxy.startPreview(mCameraView.getHolder()); // 拍照结束后继续预览
            new ImageSaveTask().execute(data); // 保存图片
        }
    };

    private class ImageSaveTask extends AsyncTask<byte[], Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(byte[]... bytes) {
            long time = System.currentTimeMillis();
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes[0], 0, bytes[0].length);
            Log.d(TAG, "BitmapFactory.decodeByteArray time: " + (System.currentTimeMillis() - time));
            int rotation = mCameraProxy.getLatestRotation();
            time = System.currentTimeMillis();
            Bitmap rotateBitmap = ImageUtils.rotateBitmap(bitmap, rotation, mCameraProxy.isFrontCamera(), true);
            Log.d(TAG, "rotateBitmap time: " + (System.currentTimeMillis() - time));
            time = System.currentTimeMillis();
            ImageUtils.saveBitmap(rotateBitmap);
            Log.d(TAG, "saveBitmap time: " + (System.currentTimeMillis() - time));
            rotateBitmap.recycle();
            return ImageUtils.getLatestThumbBitmap();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        //在相册里面选择好相片之后调回到现在的这个activity中
        switch (requestCode) {
            case IMAGE_REQUEST_CODE://这里的requestCode是我自己设置的，就是确定返回到那个Activity的标志
                if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
                    try {
                        Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);  //获取照片路径
                        cursor.close();
                        Intent intent = new Intent(this, ImagePreviewActivity.class);
                        intent.putExtra("path", path);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    public void requestWriteAndRead() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            if (mCameraProxy != null) {
                mCameraProxy.takePicture(mPictureCallback);
            }
        } else {
            boolean storageDenied = SPUtil.with(this).load().read("STORAGE_DENIED", false);
            if (storageDenied) {
                Toast.makeText(this, "没有存储权限，功能使用受限,请先授权", Toast.LENGTH_SHORT).show();
                return;
            }
            boolean store = SPUtil.with(this).load().read("STORAGE", false);
            if (!store) {
                //申请存储权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MagnifierFragment.requestCode_storage);
                return;
            }
            if (mCameraProxy != null) {
                mCameraProxy.takePicture(mPictureCallback);
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 2:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                    //拒绝存储权限
                    SPUtil.with(this).load().save("STORAGE", false);
                    SPUtil.with(this).load().save("STORAGE_DENIED", true);
                    Log.d(TAG, "拒绝存储权限");
                } else {
                    SPUtil.with(this).load().save("STORAGE", true);
                    if (mCameraProxy != null) {
                        mCameraProxy.takePicture(mPictureCallback);
                    }
                    Log.d(TAG, "同意存储权限");
                }
                break;
        }
    }
}
